package com.hz.cheetah.server;

import com.hz.cheetah.common.bean.RpcRequest;
import com.hz.cheetah.common.sys.JvmRuntime;
import com.hz.cheetah.server.imp.RpcSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * Created by yangchuan on 16/7/7.
 */
public class MessageQueueHandler {
    private static Logger logger = LoggerFactory.getLogger(MessageQueueHandler.class);

    private ThreadPoolExecutor _excutor = null;
    private BlockingQueue<Runnable> _workQueue;
    private int _idleTime;

    private RejectedExecutionHandlerImpl _rejectedExecutionHandler = new RejectedExecutionHandlerImpl();

    class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            logger.error("rejectedExecution, Runnable " + r + "executor:" + executor);
        }
    }


    public MessageQueueHandler(int maxThreadNum, int idleTime) {
        _idleTime = idleTime;
        if (maxThreadNum == 0) {
            maxThreadNum = 100;
        }
        int corepoolSize = JvmRuntime.getRuntime().getCPUsNumber();
        if (corepoolSize > maxThreadNum) {
            corepoolSize = maxThreadNum;
        }
        int keepAliveTime = 30000;
        _workQueue = new ArrayBlockingQueue<Runnable>(maxThreadNum);
        _excutor = new ThreadPoolExecutor(corepoolSize, maxThreadNum, keepAliveTime, TimeUnit.MILLISECONDS,
                _workQueue, _rejectedExecutionHandler);
    }


    public void submit(RpcSession session,Object target,RpcRequest request){
        _excutor.execute(new RpcServiceRunTask(session,target,request));
    }


}
